package com.ruoyi.websocket;

/**
 * @projectName: ruoyi
 * @package: com.ruoyi.websocket
 * @className: ChatWebSocketHandler
 * @author: 徐源长
 * @description:
 */



import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatWebSocketHandler implements WebSocketHandler {

    private final ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper用于处理JSON
    Map<String, WebSocketConnect> connects = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("新的WebSocket连接已建立，Session ID: " + session.getId());
        WebSocketConnect connect = new WebSocketConnect(session.getId());
        connects.put(session.getId(), connect); // 使用 sessionId 作为键存储连接对象
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        try {
            // 将接收到的文本消息转换为JSON对象
            String payload = (String) message.getPayload(); // 获取收到的消息（JSON字符串）
            Message receivedMessage = objectMapper.readValue(payload, Message.class); // 将消息解析为Java对象

            // 输出解析的消息内容
            System.out.println("服务器收到消息：" + receivedMessage);

            // 处理业务逻辑，生成返回消息（假设要返回一个JSON格式的消息）
            Message responseMessage = new Message();
            WebSocketConnect connect = connects.get(session.getId());
            responseMessage.setSession(session.getId());
            responseMessage.setMessage(connect.reply(receivedMessage.getMessage()));

            // 将响应消息对象转换为JSON字符串
            String responsePayload = objectMapper.writeValueAsString(responseMessage);

            // 发送JSON格式的消息
            session.sendMessage(new TextMessage(responsePayload));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 发送错误响应
                session.sendMessage(new TextMessage("{\"error\": \"Invalid message format.\"}"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("WebSocket传输错误：" + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("WebSocket连接关闭，Session ID: " + session.getId());
        // 从连接列表中移除已关闭连接的session ID
        connects.remove(session.getId());
        System.out.println("连接已移除，当前连接数: " + connects.size());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;  // 不支持消息分片
    }
}
